
//index.js
//获取应用实例
const app = getApp()
var common = require('../../utils/common.js');
var interval
Page({
  data: {
    user:[],
    nineitems:[],
    item: [],
    thisskuid: '',
    linkAppid: 'wx13e41a437b8a1d2e',
    link:'',
    titletxt: '',
    title: '我要免单',
    customerinfo:'jdd180605',
    favimg: {
      imgUrl: 'http://t.image.mrjx.51daydayup.cn/static/drawable-xxhdpi/ico5.png',
      curUrl: 'http://t.image.mrjx.51daydayup.cn/static/drawable-xxhdpi/ico5hover.png',
    },
    path: '',
    isIphoneX: false,
    isdetail: false,
    statusBarHeight: app.globalData.statusBarHeight,
    sharetc: false,
    sharepic: 'http://t.image.mrjx.51daydayup.cn/static/drawable-xxhdpi/sharetc2.png',
    sharepic2: 'http://t.image.mrjx.51daydayup.cn/static/drawable-xxhdpi/sharetc.png',
    shareData: [],
    sharereadytc: false,
    formId: '',
    sharepictc: false,
    shareimg: '',
    detailedtc: false,
    countDownHour: '36',
    countDownMinute: '00',
    countDownSecond: '00',
    totalSecond: 259200,
    inviteNum: 0,
    schedule: false,
    percent: 0,
    friends: [],
    detailedtc: false,
    hisactive: false,
    // freeId: 0,
    myactive: false,
    activestart: false,
    pageNum: 1,
    searchLoading: true,
    searchLoadingComplete: false,
    isFromSearch: true,
    loading: true,
    freeId:'',
    gameover: false,
    isFree: true,
    newuser: false,
    globalFreeid: '',
    mycenter: false,
    ismyactive: false,
    helpclick: false,
    novice: false,
    imgUrls: [
      '/img/help/4.jpg',
      '/img/help/5.jpg',
      '/img/help/6.jpg'
    ],
    step1: false,
    step2: false,
    step3: false,
    fromshare: false,
    shareEnable: false,
    thisstaractive: false,
    isfirst:true,
    zoompic: false,
    fromUserId: '',
    fromOrdinary: false,
    fromShopkeeper: false,
    isShopkeeper: false,
    isAdded: false,
    fromOf: '',
    storeManager: false,
    skuId: '',
    logined: false,
    shopHas: false,
    hasLoginTc: true,
    itemPic: [],
    thisskuid: '',
    loaded: false,
    actionSheetHidden: true,
    nologin: false,
    hasfreeid: false,
    shareItemPic: '',
    shareAvatar: '',
    dcode:'',
    friendsAvatar1: '',
    friendsAvatar2: '',
    showshareBox: false,
    imgSrcSmall: '',
    activeOver: false,
    noFreeId: false,
    activeBegin: false,
    tipfirst1: true
  },
  onShareAppMessage: function (res) {
    this.setData({
      sharetc: false
    });
    var fromOf = ''
    if(app.globalData.userInfo.hasShop){
      fromOf = 'fsk'
    }else{
      fromOf = 'fod'
    }
    path = '/pages/activeitemdetail/activeitemdetail?userId=' + app.globalData.userInfo.userId + '&sku=' + this.data.item.skuId + '&f=t&fr=' + this.data.freeId + '&fO=' + fromOf
  console.log(path)
    path = '/pages/activeitemdetail/activeitemdetail?userId=' + app.globalData.userInfo.userId + '&sku=' + this.data.item.skuId + '&f=t&fr=' + this.data.freeId + '&fO=' + fromOf
    imageUrl = this.data.item.image
    title = '快帮帮我，就差你一个了'
    if (res.from === 'button') {
      console.log(res)
      console.log(this.data.imgSrcSmall)
      imageUrl = this.data.imgSrcSmall
    }else{
      if(app.globalData.sessionId == undefined){
        wx.showModal({
          title: '提示',
          content: '您还没有登录，分享不能参加免单活动，立即登录参与面单',
          showCancel: 'false',
          success(res) {
            if (res.confirm) {
              console.log('用户点击确定')
              app.login(app.globalData.thisshareTicket)
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    }
    console.log(path)
    return {
      title: '快帮帮我，就差你一个了',
      path: path,
      imageUrl: imageUrl
    }
  },
  onLoad: function (res) {
    var that = this
    console.log(res)
    if (res) {
      if (res.fO !== undefined) {
        this.setData({
          fromOf: res.fO
        })
        console.log(this.data.fromOf)
      }
      if (res.userId !== undefined) {
        this.setData({
          fromUserId: res.userId
        })
      }
      if (res.sku !== undefined) {
        this.setData({
          skuId: res.sku
        })
      }
      if (res.skuid !== undefined) {
        this.setData({
          skuId: res.skuid
        })
      }
      if (res.fr !== undefined) {
        this.setData({
          freeId: res.fr
        })
      }
      console.log(this.data.skuId)
    }
    if(app.globalData.sessionId !== undefined){
      this.setData({
        logined: true
      })
    }else{
      this.setData({
        logined: false
      })
    }
    if(this.data.freeId !== ''){
      console.log('有freeid')
      this.setData({
        noFreeId: false,
        activeBegin: true
      })
      this.getfreestatus()
    }else{
      console.log('没有freeid')
      this.setData({
        noFreeId: true
      })
      if(app.globalData.sessionId !== undefined){
        this.setData({
          userInfo: app.globalData.userInfo
        })
        console.log('已登录')
        this.getitemstatus()
      }else{
        console.log('未登录')
        this.getitemInfo()
      }
    }
    
    if (res && this.data.fromOf == 'fod') {
      this.setData({
        fromOrdinary: true
      })
    } else if (res && this.data.fromOf == 'fsk') {
      this.setData({
        fromShopkeeper: true
      })
    } else {
      this.getShopkeeperInfo()
    }
    console.log(this.data.fromShopkeeper)
    this.getnineitemdata()
    wx.getStorage({
      key: 'tipfirst1',
      success (res) {
        console.log(res.data)
        that.setData({
          tipfirst1: res.data
        })
        console.log(that.data.tipfirst1)
      }
    })
  },
  onShow: function (res) {
    console.log('res')
    console.log(res)
    var that = this;
    // wx.hideHomeButton()
  },
  active(){
    var that = this
    if (that.data.globalFreeid && !this.data.myactive) {
      console.log('dsasda')
      that.staractive()
    } else if (this.data.myactive) {
      that.setData({
        myactive: true,
        user: app.globalData.userInfo,
        formId: app.globalData.formId
      })
      that.staractive()
    } else if (this.data.mycenter) {
      console.log(1)
      console.log(app.globalData.ufid)
      that.setData({
        user: getApp().globalData.userInfo,
        freeId: app.globalData.ufid,
        activestart: true
      })
      console.log(1)
      that.getfreestatus()
    } else {
      that.setData({
        user: getApp().globalData.userInfo
      })
      that.getitemstatus()
    }
    console.log(this.data.freeId)
  },
  // 订阅服务授权
  sq(){
    wx.requestSubscribeMessage({
      tmplIds: ['P9ELCgIFPvT_SgO3Ti5JIg6fJgcX86blOrObYFIK9NU'],
      success(res) {
        console.log(res)
      },
      fail(res) {
        console.log(res)
      }
    })
  },
  //通过freeId获取免单信息
  getfreestatus(){
    const that = this
    common.post({
      url: '/app/user/activity/getFreeInfo', data: { freeId: this.data.freeId }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          console.log('获取免单信息')
          if (res.data.data.sku.images) {
            var imgstr = JSON.parse(res.data.data.sku.images)
            console.log(imgstr)
          }
          if(res.data.data.inviter.hasShop){
            that.setData({
              fromShopkeeper: true
            })
          }else{
            that.setData({
              fromShopkeeper: false
            })
          }
          var inviteNum
          that.setData({
            inviter: res.data.data.inviter,
            friends: res.data.data.users,
            item: res.data.data.sku,
            totalSecond: res.data.data.remainSec,
            item: res.data.data.sku,
            itemPic: imgstr,
          });
          if (res.data.data.inviteNum > 3) {
            inviteNum = 3
          } else {
            inviteNum = res.data.data.inviteNum
          }
          if(app.globalData.sessionId !== undefined){
            console.log('已登录')
            that.getitemlink()
            this.setData({
              userInfo:app.globalData.userInfo,
              nologin: false
            })
            if(app.globalData.userInfo.userId == that.data.fromUserId){
              that.setData({
                myactive: true
              })
              console.log('myactive')
              if(inviteNum > 2 && that.data.myactive){
                that.setData({
                  activeSuccess: true
                })
                wx.showModal({
                  title: '提示',
                  content: '您已经凑够人数，请立即购买，购买成功，审核后将返还等价的现金，可提现',
                  confirmText: '确定',
                  showCancel: false,
                  success: function (res) {
                    if (res.confirm) {
                      console.log('用户点击确定')
                    }
                  }
                })
              }
            }else{
              that.setData({
                hisactive: true
              })
            }
          }else{
            console.log('未登录')
            this.setData({
              nologin: true,
            })
          }
          console.log(that.data.totalSecond)
          that.countDown()
          // if (!that.data.hisactive) {
          //   that.setData({
          //     activestart: true
          //   });
          // }
          console.log('myactive:' + that.data.myactive)
          console.log('hisactive:' + that.data.hisactive)
          // if (data.data.data.isFree && data.data.data.orderId !== null) {
          //   console.log('percent:' + that.data.percent)
          //   that.setData({
          //     totalSecond: data.data.data.remainSec,
          //     inviteNum: inviteNum,
          //     schedule: true,
          //     percent: 100,
          //   });
          //   console.log(that.data.hisactive)
          //   if (that.data.hisactive) {

          //   } else {
          //     wx.showModal({
          //       title: '提示',
          //       content: '免单成功，返还积分可在“我的”中查看和提现',
          //       confirmText: '立即提现',
          //       cancelText: '看看别的',
          //       success: function (res) {
          //         if (res.confirm) {
          //           wx.reLaunch({
          //             url: '/pages/usercenter/usercenter'
          //           })
          //         }
          //       }
          //     })
          //   }
          // }
          // console.log('percent:' + that.data.percent)
          // console.log(that.data.thisstaractive)
          // if (that.data.thisstaractive) {

          // } else {
          //   that.staractive()
          // }
        }
      }).catch((res) => {
        console.log(res)
      })
  },
  buybtn(e) {
    console.log(e)
    app.globalData.item = e.currentTarget.dataset.item
    app.globalData.freeid = ''
    console.log(app.globalData.item)
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: {
        formid: e.detail.formId,
        sessionId: app.globalData.sessionId
      },
      url: app.globalData.url + "/wxa/user/uploadFormid",
      async: true,
      timeout: 10000,
      success: function (data) {
        wx.navigateTo({
          url: '/pages/activeitemdetail/activeitemdetail?sku=' + e.currentTarget.dataset.item.skuId + '&fr='
        })
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        wx.hideLoading()
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })

  },
  buybtn1(){
    if(app.globalData.sessionId){
      console.log(e)
      app.globalData.item = e.currentTarget.dataset.item
      app.globalData.freeid = ''
      console.log(app.globalData.item)
      const requestTask = wx.request({
        method: "POST",
        header: { "content-type": "application/x-www-form-urlencoded" },
        data: {
          formid: e.detail.formId,
          sessionId: app.globalData.sessionId
        },
        url: app.globalData.url + "/wxa/user/uploadFormid",
        async: true,
        timeout: 10000,
        success: function (data) {
          wx.navigateTo({
            url: '/pages/activeitemdetail/activeitemdetail?sku=' + e.currentTarget.dataset.item.skuId + '&fr='
          })
        },
        error: function (textStatus) {
          console.error(textStatus);
        },
        complete: function (XMLHttpRequest, status) {
          wx.hideLoading()
          if (status == 'timeout') {
            requestTask.abort()    // 超时后中断请求
            wx.showModal({
              title: '提示',
              content: '网络超时，请重试',
              showCancel: 'false',
              success: function (res) {
                if (res.confirm) {
                  wx.redirectTo({
                    url: '/pages/index/index'
                  })
                }
              }
            })
          }
        }
      })
    }else{
      this.loginTip()
    }
  },
  sharertc(){
    this.setData({
      sharetc: true
       });
  },
  ruletc() {
    // this.setData({
    //   detailedtc: true
    // });
    wx.navigateTo({
      url: '/pages/help/help'
    })
  },
  closedtc(){
    this.setData({
      detailedtc: false
    });
  },
  getnineitemdata() {
    const that = this
    isChoiceness = false
    common.post({
      url: '/app/v2/goods/freeShipping99', data: { pageNo: 1,sessionId:app.globalData.sessionId}
    })
      .then((res) => {
        that.setData({
          nineitems: res.data.data,
        });
        console.log(that.data.nineitems)
      }).catch((res) => {
        console.log(res)
      })
  },
  getnineitemdatapage() {
    const that = this;
    var page = that.data.pageNum + 1;
    common.post({ url: '/app/v2/goods/freeShipping99', data: {pageNo: page,sessionId:app.globalData.sessionId } })
      .then((res) => {
        var data = that.data.nineitems;
        console.log(res.data)
        if (that.data.pageNum * 10 < res.data.total) {
          that.setData({
            pageNum: page
          });
          var postList = res.data.data;
          for (let i = 0; i < postList.length; i++) {
            let tmp = postList[i];
            data.push(tmp);
          }
          setTimeout(() => {
            console.log(data)
            that.setData({
              nineitems: data,
            })
          }, 300);
        } else {
          console.log('没有了')
          that.setData({
            loading: false
          })
          wx.showToast({
            title: '没有了',
            icon: 'none',
            duration: 2000
          })
        }

      }).catch((res) => {
        console.log(res)

      })
  },
  onReachBottom(){
    console.log('bottom')
    this.getnineitemdatapage()
  },
  getitemstatus() {
    const that = this
    isChoiceness = false
    common.post({
      url: '/app/user/activity/checkFreeInfo', data: { sessionId: app.globalData.sessionId,skuId: this.data.skuId, }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0){
          if (res.data.data.sku.images) {
            var imgstr = JSON.parse(res.data.data.sku.images)
            console.log(imgstr)
          }
          that.setData({
            freeId: res.data.data.freeId,
            shareEnable: app.globalData.shareEnable,
            activeBegin: false,
            item: res.data.data.sku,
            itemPic: imgstr
          });
          var inviteNum
          if (res.data.data.inviteNum > 0 && res.data.data.users.length > 0) {
            that.setData({
              friends: res.data.data.users
            });
          }
          if (res.data.data.inviteNum > 3) {
            inviteNum = 3
          } else {
            inviteNum = res.data.data.inviteNum
          }
          if (res.data.data.isFree && res.data.data.orderId !== null) {
            that.setData({
              totalSecond: res.data.data.remainSec,
              inviteNum: inviteNum,
              schedule: true,
              percent: 100,
            });
            wx.showModal({
              title: '提示',
              content: '免单成功，返还现金可在“我的”中查看和提现',
              confirmText: '查看返现',
              cancelText: '看看别的',
              success: function (res) {
                if (res.confirm) {
                  wx.reLaunch({
                    url: 'pages/usercenter/usercenter'
                  })
                } else if (res.cancel) {
                  wx.reLaunch({
                    url: '/pages/itemlist/itemlist'
                  })
                }
              }
            })
          } else if (res.data.data.isBuy) {
            that.setData({
              totalSecond: res.data.data.remainSec,
              inviteNum: inviteNum,
              schedule: true,
              percent: 50
            });
          } else {
            that.setData({
              totalSecond: res.data.data.remainSec,
              inviteNum: inviteNum,
              schedule: true,
              percent: 26
            });
          }
          console.log(that.data.totalSecond)
          that.setData({
            activestart: true
          });
          that.countDown()
        }else if(res.data.code == 1){
          that.getitemInfo()
        }
      }).catch((res) => {
        console.log(res)
      })
  },
  getfreeinfo() {
    var that = this
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: {
        sessionId: app.globalData.sessionId,
        skuId: app.globalData.item.skuId,
        formId: that.data.formId
      },
      url: app.globalData.url + "/app/v2/goods/getShareLink",
      async: true,
      timeout: 10000,
      success: function (data) {
        console.log(data)
        if(data.data.code == 0){
          if (data.data.data.freeId) {
            that.setData({
              freeId: data.data.data.freeId
            });
          }
        }else{
          
        }
        
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        wx.hideLoading()
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  startbtn(e){
    console.log(e)
    var that = this
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: {
        skuId: app.globalData.transferskuId
      },
      url: app.globalData.url + "/app/goods/getSkuInfoBySkuId",
      async: true,
      timeout: 10000,
      success: function (data) {
        console.log(data)
        if (data.data.code == 0) {
          that.setData({
            item: data.data.sku
          });
          console.log(that.data.isfree)
          if (that.data.isfree) {
            app.globalData.formId = e.detail.formId
            wx.navigateTo({
              url: '/pages/activeitemdetail/activeitemdetail?myactive=true&skuid=' + that.data.item.skuId
            })
          } else {
            wx.showModal({
              title: '提示',
              content: '此商品免单活动已结束，快去看看其他商品吧',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  // wx.reLaunch({
                  //   url: '/pages/itemlist/itemlist?active=true'
                  // })
                }
              }
            })
          }
        } else {
          getApp().globalData.freeid = ''
          getApp().globalData.fromactive = false
          wx.showModal({
            title: '提示',
            content: '此商品已被抢光，去看看其他的免单商品吧',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.reLaunch({
                  url: '/pages/itemlist/itemlist?active=true'
                })
              }
            }
          })
        }
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
    
  },
  // 选择画布
  canvas(){
    wx.showLoading({
      title: '活动开启中',
      mask: true
    })
    console.log('选择画布')
    const query = wx.createSelectorQuery();//如果是在组件中，则改成 this.createSelectorQuery()
    query.select('#canvas').fields({
      node: true,
      rect: true
    }, res => {
      const canvas = res.node;
      const ctx = canvas.getContext('2d');
      canvas.width = 828;//本地图像的width
      canvas.height = 1472;//本地图像的height
      this.render(canvas, ctx);
    }).exec()
  },
  canvas1(){
    console.log('选择画布')
    const query = wx.createSelectorQuery();//如果是在组件中，则改成 this.createSelectorQuery()
    query.select('#canvas1').fields({
      node: true,
      rect: true
    }, res => {
      const canvas = res.node;
      const ctx = canvas.getContext('2d');
      canvas.width = 500;//本地图像的width
      canvas.height = 400;//本地图像的height
      this.render2(canvas, ctx);
    }).exec()
  },
 
  // 生成分享图

  render(canvas, ctx) {
    const that = this
    this.drawIteminfo(ctx,canvas).then(function(){
      console.log('第一步完成')
      that.drawItemPic(ctx,canvas).then(function(){
        console.log('第二步完成')
        that.drawItemTag(ctx,canvas).then(function(){
          console.log('第三步完成')
          that.drawAvatar(ctx,canvas).then(function(){
            console.log('第四步完成')
            that.drawDcode(ctx,canvas).then(function(){
              console.log('第五步完成')
              if(that.data.friends.length == 0){
                that.drawFriends(ctx,canvas).then(function(){
                  console.log('第六步完成，已生成分享大图')
                  that.drawCanvas(canvas)
                  console.log('开始生成分享小图')
                  that.canvas1()
                })
              }else if(that.data.friends.length == 1){
                that.drawFriends1(ctx,canvas).then(function(){
                  console.log('第六步完成')
                  that.drawFriendsBig1(ctx,canvas).then(function(){
                    console.log('第七步完成，已生成分享大图')
                    that.drawCanvas(canvas)
                    console.log('开始生成分享小图')
                    that.canvas1()
                  })
                })
              }else if(that.data.friends.length >= 2){
                that.drawFriends2(ctx,canvas).then(function(){
                  console.log('第六步完成')
                  that.drawFriendsBig1(ctx,canvas).then(function(){
                    console.log('第七步完成')
                    that.drawFriendsBig2(ctx,canvas).then(function(){
                      console.log('第八步完成，已生成分享大图')
                      that.drawCanvas(canvas)
                      console.log('开始生成分享小图')
                      that.canvas1()
                    })
                  })
                })
              }
            })
          })
        })
      })
    })
  },
  render2(canvas, ctx){
    const that = this
    that.drawSmallpic(ctx,canvas).then(function(){
      console.log('第一步完成')
      that.drawSmalltag(ctx,canvas).then(function(){
        console.log('第二步完成')
        if(that.data.friends.length == 0){
          that.drawSmallFriend(ctx,canvas).then(function(){
            console.log('完成绘制')
            that.drawCanvas2(canvas)
          })
        }else if(that.data.friends.length == 1){
          that.drawSmallFriend1(ctx,canvas).then(function(){
            console.log('第三步完成')
            that.drawOneFriend1(ctx,canvas).then(function(){
              console.log('完成绘制')
              that.drawCanvas2(canvas)
            })
            
          })
        }else if(that.data.friends.length >= 2){
          that.drawSmallFriend2(ctx,canvas).then(function(){
            console.log('第三步完成')
            that.drawOneFriend1(ctx,canvas).then(function(){
              console.log('第四步完成')
              that.drawOneFriend2(ctx,canvas).then(function(){
                console.log('完成绘制')
                that.drawCanvas2(canvas)
              })
            })
          })
        }
      })
    })
  },
  // 绘制分享小图
  drawSmallpic(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 0, 0, 500, 500);
        ctx.fillStyle = '#FFE232'
        ctx.fillRect(0,320,500,80)
        ctx.font = "bold 24px PingFangSC-Semibold";
        ctx.fillStyle = "#000";
        ctx.textAlign = 'left';
        ctx.fillText('3人帮TA助力就免费得', 16, 368);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = that.data.item.image
    })
  },
  // 绘制商品标签
  drawSmalltag(ctx,canvas){
    const that = this
    var goodCommentsRate = '100'
    if(this.data.item.goodCommentsRate > 0){
      goodCommentsRate = this.data.item.goodCommentsRate
    }
    var txt = '好评率' + goodCommentsRate + '%'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 12, 12, 200, 36);
        ctx.font = "20px PingFangSC-Medium";
        ctx.fillStyle = "#FF5555";
        ctx.textAlign = 'center';
        ctx.fillText(txt, 146, 38);
        ctx.fillStyle = "#fff";
        ctx.fillText('京东', 46, 38);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/item_tag.png'
    })
  },
  // 绘制小图头像
  drawSmallFriend(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        if(that.data.friends.length == 0){
          ctx.drawImage(img, 276, 328, 64, 64);
          ctx.drawImage(img, 348, 328, 64, 64);
          ctx.drawImage(img, 420, 328, 64, 64);
          ctx.font = "bold 26px PingFangSC-Semibold";
          ctx.fillStyle = "#000";
          ctx.textAlign = 'center';
          ctx.fillText('1', 308, 368);
          ctx.fillText('2', 380, 368);
          ctx.fillText('3', 452, 368);
        }
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/pel_share_b@3x.png'
    })
  },
  // 小图一个好友时候
  drawSmallFriend1(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        if(that.data.friends.length == 1){
          ctx.drawImage(img, 348, 328, 64, 64);
          ctx.drawImage(img, 420, 328, 64, 64);
          ctx.font = "bold 26px PingFangSC-Semibold";
          ctx.fillStyle = "#fff";
          ctx.textAlign = 'center';
          ctx.fillText('2', 380, 368);
          ctx.fillText('3', 452, 368);
        }
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/pel_share_b@3x.png'
    })
  },
  // 小图两个好友时候
  drawSmallFriend2(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        if(that.data.friends.length >= 2){
          ctx.drawImage(img, 420, 328, 64, 64);
          ctx.font = "bold 26px PingFangSC-Semibold";
          ctx.fillStyle = "#fff";
          ctx.textAlign = 'center';
          ctx.fillText('3', 452, 368);
        }
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/pel_share_b@3x.png'
    })
  },
  // 绘制小图一个好友头像
  drawOneFriend1(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        if(that.data.friends.length >= 1){
          ctx.beginPath()
          let r = 32, x = 276, y = 328
          ctx.save()
          ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
          ctx.clip()
          ctx.drawImage(img, 276, 328, 64, 64);
          ctx.restore()
          ctx.strokeStyle = "white";
          ctx.lineWidth = '2'
          ctx.stroke();
        }
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = that.data.friends[0].avatar
    })
  },
  // 绘制小图两个好友头像
  drawOneFriend2(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        if(that.data.friends.length >= 1){
          ctx.beginPath()
          let r = 32, x = 348, y = 328
          ctx.save()
          ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
          ctx.clip()
          ctx.drawImage(img, 348, 328, 64, 64);
          ctx.restore()
          ctx.strokeStyle = "white";
          ctx.lineWidth = '2'
          ctx.stroke();
        }
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = that.data.friends[1].avatar
    })
  },
  // 绘制好友
  drawFriends(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img2 = canvas.createImage();
      var str = '待助力'
      img2.onload = (e) => {
        console.log('img2 loaded')
        ctx.drawImage(img2, 190, 1060, 96, 96);
        ctx.drawImage(img2, 366, 1060, 96, 96);
        ctx.drawImage(img2, 542, 1060, 96, 96);
        ctx.font = "bold 23px PingFangSC-Semibold";
        ctx.fillStyle = "#FF5555";
        ctx.textAlign = 'center';
        ctx.fillText(str, 239, 1184);
        ctx.fillText(str, 415, 1184);
        ctx.fillText(str, 595, 1184);
        resolve()
      }
      img2.onerror = (e) => {
        console.error('err:', e)
      }
      img2.src = '/img/new/people_redbg@3x.png'
    })
  },
  // 大图一个好友时候
  drawFriends1(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img2 = canvas.createImage();
      var str = '待助力'
      img2.onload = (e) => {
        console.log('img2 loaded')
        ctx.drawImage(img2, 366, 1060, 96, 96);
        ctx.drawImage(img2, 542, 1060, 96, 96);
        ctx.font = "bold 23px PingFangSC-Semibold";
        ctx.fillStyle = "#FF5555";
        ctx.textAlign = 'center';
        ctx.fillText(str, 415, 1184);
        ctx.fillText(str, 595, 1184);
        resolve()
      }
      img2.onerror = (e) => {
        console.error('err:', e)
      }
      img2.src = '/img/new/people_redbg@3x.png'
    })
  },
  // 大图两个好友时候
  drawFriends2(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img2 = canvas.createImage();
      var str = '待助力'
      img2.onload = (e) => {
        console.log('img2 loaded')
        ctx.drawImage(img2, 542, 1060, 96, 96);
        ctx.font = "bold 23px PingFangSC-Semibold";
        ctx.fillStyle = "#FF5555";
        ctx.textAlign = 'center';
        ctx.fillText(str, 595, 1184);
        resolve()
      }
      img2.onerror = (e) => {
        console.error('err:', e)
      }
      img2.src = '/img/new/people_redbg@3x.png'
    })
  },
  // 一个大图好友头像
  drawFriendsBig1(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img2 = canvas.createImage();
      var str = that.data.friends[0].nickname
      img2.onload = (e) => {
        console.log('img loaded')
        ctx.beginPath()
        let r = 48, x = 190, y = 1060
        ctx.save()
        ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
        ctx.clip()
        ctx.drawImage(img2, 190, 1060, 96, 96);
        ctx.restore()
        ctx.strokeStyle = "white";
        ctx.lineWidth = '2'
        ctx.stroke();
        ctx.font = "bold 23px PingFangSC-Semibold";
        ctx.fillStyle = "#FF5555";
        ctx.textAlign = 'center';
        ctx.fillText(str, 239, 1184);
        resolve()
      }
      img2.onerror = (e) => {
        console.error('err:', e)
      }
      img2.src = that.data.friends[0].avatar
    })
  },
  // 两个大图好友头像
  drawFriendsBig2(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img2 = canvas.createImage();
      var str = that.data.friends[1].nickname
      img2.onload = (e) => {
        ctx.beginPath()
        let r = 48, x = 366, y = 1060
        ctx.save()
        ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
        ctx.clip()
        ctx.drawImage(img2, 366, 1060, 96, 96);
        ctx.restore()
        ctx.strokeStyle = "white";
        ctx.lineWidth = '2'
        ctx.stroke();
        ctx.font = "bold 23px PingFangSC-Semibold";
        ctx.fillStyle = "#FF5555";
        ctx.textAlign = 'center';
        ctx.fillText(str, 415, 1184);
        resolve()
      }
      img2.onerror = (e) => {
        console.error('err:', e)
      }
      img2.src = that.data.friends[1].avatar
    })
  },
  // 绘制内容
  drawIteminfo(ctx,canvas){
    console.log('开始绘图')
    var row1size = function (name) {
      var str = name;
      // str = str.slice(0, 36) + '...';
      length = 0.0;
      finalStr = "";
      for (i = 0; i < name.length; i++) {
        if (name[i].match("[0-9a-zA-Z]") || name[i] == " ") {
          length += 0.5;
        } else {
          length += 1;
        }

        finalStr += name[i];
        if (length > 18) {
          break;
        }
      }
      return finalStr;
    }
    var row2size = function (name) {
      var str = name;
      // str = str.slice(0, 36) + '...';
      length = 0.0;
      finalStr = "";
      for (i = 0; i < name.length; i++) {
        if (name[i].match("[0-9a-zA-Z]") || name[i] == " ") {
          length += 0.5;
        } else {
          length += 1;
        }
        if (length > 19) {
          finalStr += name[i];
        }
        if (length > 35) {
          break;
        }
      }
      return finalStr + '...';
    }
    console.log(this.data.item)
    var itemName = this.data.item.title
    var str1 = row1size(itemName)
    var str2 = row2size(itemName)
    let that = this;
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();//canvas 2d 通过此函数创建一个图片对象
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 0, 0, 828, 1472);
        ctx.font = "30px PingFangSC-Medium";
        ctx.fillStyle = "#363636";
        ctx.textAlign = 'center';
        ctx.fillText(str1, 414, 904);
        ctx.fillText(str2, 414, 946);
        ctx.font = "32px PingFangSC-Regular";
        ctx.fillStyle = "#FF5555";
        ctx.fillText('3人助力TA就免费得', 414, 1022);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/zc_share@3x.jpg'
    })
  },
  // 绘制商品图
  drawItemPic(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        var x = 134,y = 264, r = 8, w = 560, h = 560
        ctx.save()
        // ctx.beginPath()
        // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
        // 这里是使用 fill 还是 stroke都可以，二选一即可
        ctx.setFillStyle = 'transparent'
        // ctx.setStrokeStyle('transparent')
        // 左上角
        ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
        // 右上角
        ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
        // 右下角
        ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
        // 左下角
        ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
        // ctx.stroke()
        ctx.closePath()
        // 剪切
        ctx.clip()
        ctx.drawImage(img, 134, 264, 560, 560);
        ctx.restore();
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = that.data.item.image
    })
  },
  // 绘制标签
  drawItemTag(ctx,canvas){
    const that = this
    var goodCommentsRate = '100'
    if(this.data.item.goodCommentsRate > 0){
      goodCommentsRate = this.data.item.goodCommentsRate
    }
    var txt = '好评率' + goodCommentsRate + '%'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 292, 798, 244, 52);
        ctx.font = "26px PingFangSC-Medium";
        ctx.fillStyle = "#FF5555";
        ctx.textAlign = 'center';
        ctx.fillText(txt, 454, 834);
        ctx.fillStyle = "#fff";
        ctx.fillText('京东', 330, 834);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/item_tag.png'
    })
  },
  // 绘制头像
  drawAvatar(ctx,canvas){
    const that = this
    let txt1 = app.globalData.userInfo.nickname + ' 邀请你0元得好物',
        txt2 = '长按识别二维码进入京多多'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.beginPath()
        let r = 46, x = 42, y = 1318
        ctx.save()
        ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
        ctx.clip()
        ctx.drawImage(img, x, y, 92, 92);
        ctx.restore()
        ctx.strokeStyle = "white";
        ctx.lineWidth = '2'
        ctx.stroke();
        if(app.globalData.isIphone){
          ctx.font = "26px PingFangSC-Medium";
        }else{
          ctx.font = "26px NotoSans-Medium";
        }
        ctx.fillStyle = "#fff";
        ctx.textAlign = 'left';
        ctx.fillText(txt1, 148, 1358);
        if(!app.globalData.isIphone){
          ctx.font = "26px PingFangSC-Light";
        }else{
          ctx.font = "lighter 26px NotoSans";
        }
        ctx.fillText(txt2, 148, 1394);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = app.globalData.userInfo.avatar
    })
  },
  // 绘制二维码
  drawDcode(ctx,canvas){
    const that = this
    if(app.globalData.userInfo.hasShop){
      fromOf = '&fO=fsk'
    }else{
      fromOf = '&fO=fod'
    }
    return new Promise(function (resolve, reject) {
      var scene = 'userId=' + app.globalData.userInfo.userId + '&sku=' + that.data.item.skuId + '&fr=' + that.data.freeId
      common.post({
        url: '/wxa/qrcode/getUnlimitQrcode', 
        data: {
          scene: scene,
          page: 'pages/activeitemdetail/activeitemdetail',
          sessionId: app.globalData.sessionId,
          width: '236',
          auto_color: 'false',
          line_color: '{"r":"255","g":"85","b":"85"}',
          is_hyaline: 'false'
        }
      })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          console.log(res.data)
          console.log(res.data.qrcodeLink)
          let img = canvas.createImage();
          img.onload = (e) => {
            console.log('img loaded')
            ctx.beginPath()
            let r = 68, x = 652, y = 1296
            ctx.save()
            ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
            ctx.fillStyle = 'white'
            ctx.fill()
            ctx.clip()
            ctx.drawImage(img, x + 7, y + 7, 122, 122);
            ctx.restore()
            resolve()
          }
          img.onerror = (e) => {
            console.error('err:', e)
          }
          img.src = res.data.qrcodeLink
        }
      }).catch((res) => {
        console.log(res)
        app.timeOutTip()
      })
    })
  },
  // 生成图片
  drawCanvas(canvas){
    const that = this
    let promise = new Promise(function (resolve, reject) {
      wx.canvasToTempFilePath({
        canvas,
        wwidth: 828,
        height: 1472,
        destWidth:828,
        destHeight:1472,
        success(res) {
          console.log(res.tempFilePath)
          that.setData({
            imgSrc:res.tempFilePath,
          })
          wx.hideLoading()
        }
      })
    })
  },
  drawCanvas2(canvas){
    const that = this
    let promise = new Promise(function (resolve, reject) {
      wx.canvasToTempFilePath({
        canvas,
        wwidth: 500,
        height: 400,
        destWidth:500,
        destHeight:400,
        success(res) {
          console.log(res.tempFilePath)
          that.setData({
            imgSrcSmall:res.tempFilePath,
            showshareBox: true
          })
          wx.hideLoading()
        }
      })
    })
  },
  // 免单开始
  freeActiveStart(e){
    console.log('click')
    if(app.globalData.sessionId !== undefined){
      console.log(e)
      this.setData({
        activestart: true
      });
      this.staractive()
    }else{
      wx.showModal({
        title: '提示',
        content: '你需要登录，才能享受优惠',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
            app.login(app.globalData.thisshareTicket)
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },
  
  staractive() {
    this.setData({
      thisstaractive: true,
      shareEnable: app.globalData.shareEnable
    });
    console.log(this.data.item)
    this.sq()
    const that = this
    common.post({
      url: '/app/v2/goods/getShareLink', data: { sessionId: app.globalData.sessionId,skuId: that.data.skuId, }
    })
    .then((res) => {
      console.log(res.data)
      if (res.data.code == 0) {
        that.setData({
          freeId: res.data.data.freeId
        });
        that.countDown()
        console.log(that.data.freeId)
        // this.loadImg();
        this.canvas()
      }
    }).catch((res) => {
      console.log(res)
    })
  
  },
  helpclick(){
    var that = this
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: {
        freeId: that.data.globalFreeid
      },
      url: app.globalData.url + "/app/user/activity/getFreeInfo",
      async: true,
      timeout: 10000,
      success: function (data) {
        console.log(data)
        that.setData({
          friends: data.data.data.users,
          helpclick: false
        });
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        wx.hideLoading()
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  countDown() {
    console.log('开启倒计时')
    console.log(interval)
    const that = this
    // console.log(this.data.user)
    clearInterval(interval)
    var totalSecond = this.data.totalSecond
    interval = setInterval(function () {
      // 秒数
      var second = totalSecond;
      // 天数位
      var day = Math.floor(second / 3600 / 24);
      var dayStr = day.toString();
      if (dayStr.length == 1) dayStr = '0' + dayStr;

      // 小时位
      var hr = Math.floor((second) / 3600);
      var hrStr = hr.toString();
      if (hrStr.length == 1) hrStr = '0' + hrStr;

      // 分钟位
      var min = Math.floor((second - hr * 3600) / 60);
      var minStr = min.toString();
      if (minStr.length == 1) minStr = '0' + minStr;

      // 秒位
      var sec = second - hr * 3600 - min * 60;
      var secStr = sec.toString();
      if (secStr.length == 1) secStr = '0' + secStr;

      this.setData({
        countDownDay: dayStr,
        countDownHour: hrStr,
        countDownMinute: minStr,
        countDownSecond: secStr,
      });
      // console.log('countDownHour:' + this.data.countDownHour)
      totalSecond--;
      if (totalSecond < 0) {
        clearInterval(interval);
        that.setData({
          activeOver: true
        })
        if(app.globalData.sessionId !== undefined){
          wx.showModal({
            title: '提示',
            content: '此商品免单活动已结束',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                // wx.reLaunch({
                //   url: '/pages/itemlist/itemlist?active=true'
                // })
              }
            }
          })
        }
        
        this.setData({
          countDownDay: '00',
          countDownHour: '00',
          countDownMinute: '00',
          countDownSecond: '00',
          activestart: false,
          hisactive: false,
          gameover: true
        });
      }
    }.bind(this), 1000);
  },
  closedtc() {
    this.setData({
      detailedtc: false
    });
  },
  homelink(){
    wx.reLaunch({
      url: '/pages/itemlist/itemlist?active=true'
    })
  },
  getclipboarddata(content) {
    wx.showLoading({
      title: '加载中',
    })
    var that = this
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: {
        content: content
      },
      url: app.globalData.url + "/app/v2/goods/clipboardSpirit",
      async: true,
      timeout: 10000,
      success: function (data) {
        wx.hideLoading()
        console.log(data)
        if (data.data.code == 0) {
          if (data.data.data.isFind) {
            that.setData({
              cbitem: data.data.data,
              cbsw: true,
              isFind: true
            });
          } else {
            that.setData({
              cbitem: data.data.data,
              cbsw: true,
              isFind: false
            });
          }
          console.log(that.data.cbitem)
        }
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        wx.hideLoading()
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  getitemlink() {
    const that = this;
    var couponId
    if (this.data.item.coupons) {
      couponId = this.data.item.coupons[0].couponId
    } else {
      couponId = ''
    }
    common.post({ url: '/app/goods/getLink', 
      data: { 
        skuId: this.data.item.skuId,
        couponId: couponId,
        sessionId: app.globalData.sessionId,
        pUserId: this.data.fromUserId
      } 
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          that.setData({
            link: res.data.link,
            loaded: true
          });
          var link = encodeURIComponent(that.data.link)
          var path = '/pages/product/product?wareId=' + that.data.item.sku + '&spreadUrl=' + link + '&customerinfo=' + that.data.customerinfo
          console.log(path)
          that.setData({
            path: path,
            logined: true
          });

        } else if(res.data.code == -9998){
          console.log(res)
          that.loginTip()
        }
      }).catch((res) => {
        console.log(res)

      })
  },
  postformid(skuId) {
    var that = this
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: {
        sessionId: app.globalData.sessionId,
        skuId: skuId,
        formId: app.globalData.formId
      },
      url: app.globalData.url + "/app/goods/getShareLink",
      async: true,
      timeout: 10000,
      success: function (data) {
        console.log(data)
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        wx.hideLoading()
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  formSubmit(e) {
    console.log(e)
    this.setData({
      sharetc: true,
      shareData: e.currentTarget.dataset.item,
      formId: e.detail.formId
    });
    console.log(this.data.shareData)
  },
  closestc() {
    this.setData({
      sharetc: false,
      shareData: []
    });
  },
  closertc() {
    this.setData({
      sharereadytc: false,
    });
  },
  closesptc() {
    this.setData({
      sharepictc: false,
      shareimg: ''
    });
  },
  saveimg() {
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: this.data.shareimg,
      success(res) {
        wx.hideToast()
        app.globalData.newnotice = true
        that.setData({
          news: app.globalData.newnotice
        });
        console.log(that.data.news)
        wx.showModal({
          title: '提示',
          content: '分享图已经存到您的相册',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
              that.setData({
                sharepictc: false,
                shareimg: ''
              });
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
    })
  },
  shareweixinquan(e) {
    console.log(this.data.freeId)
    wx.navigateTo({
      url: '/pages/shareimage/shareimage?freeId=' + this.data.freeId  
    })
  },
  favitem(e) {
    var that = this
    console.log(e)
    var edata = e.currentTarget.dataset;
    var i = edata.index
    console.log(edata)
    const requestTask = wx.request({
      method: "POST",
      header: { "content-type": "application/x-www-form-urlencoded" },
      data: { skuId: edata.skuid, sessionId: app.globalData.sessionId },
      url: app.globalData.url + "/app/user/collect",
      async: true,
      timeout: 10000,
      success: function (data) {
        console.log(data)
        if (edata.iscollect) {
          wx.showToast({
            title: '取消收藏',
            icon: "success"
          })
          var currId = edata.skuid;
          var array = that.data.item;
          array.isCollect = false;
          array.collectTotal = array.collectTotal - 1;
          that.setData({
            item: array
          });
          return false
        } else {
          wx.showToast({
            title: '收藏成功',
            icon: "success"
          })
          var currId = edata.skuid;
          var array = that.data.item;
          array.isCollect = true;
          array.collectTotal = array.collectTotal + 1;
          that.setData({
            item: array
          });
          return false
        }
      },
      error: function (textStatus) {
        console.error(textStatus);
      },
      complete: function (XMLHttpRequest, status) {
        if (status == 'timeout') {
          requestTask.abort()    // 超时后中断请求
          wx.showModal({
            title: '提示',
            content: '网络超时，请重试',
            showCancel: 'false',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index'
                })
              }
            }
          })
        }
      }
    })
  },
  fetchSearchList: function (e) {
    console.log(e)
    var that = this;
    var pageNum = that.data.pageNum//把第几次加载次数作为参数  
    that.setData({
      pageNum: pageNum
    });
    console.log(pageNum)
    var isChoiceness = true
    this.getnineitemdata(pageNum)
  },
   usercenterlink: function () {
    wx.reLaunch({
      url: '/pages/usercenter/usercenter'
    })
  },
  back: function () {
    console.log(app.globalData.isdetail)
    if (app.globalData.isdetail && typeof (app.globalData.isdetail) !== "undefined" && !this.data.myactive){
      app.globalData.isdetail = false
      wx.redirectTo({
        url: '/pages/itemlist/itemlist'
      })
    } else if (app.globalData.isdetail && typeof (app.globalData.isdetail) !== "undefined" && this.data.myactive){
      wx.navigateBack()
    } else if (this.data.globalFreeid) {
      wx.redirectTo({
        url: '/pages/itemlist/itemlist'
      })
    }else{
      wx.navigateBack()
    }
  },
  imgzoom() {
    this.setData({
      zoompic: true
    });
  },
  closedztc(){
    this.setData({
      zoompic: false
    });
  },
  buybtnlink: function() {
    if(app.globalData.userId){
      if(this.data.path !== ''){
        wx.navigateToMiniProgram({
          appId: this.data.linkAppid,
          path: this.data.path,
          extraData: {
            foo: 'bar'
          },
          success(res) {
            // 打开成功
          }
        })
      }else{
        wx.showModal({
          title: '提示',
          content: '连接生成中，请稍后再试',
          success(res) {
            if (res.confirm) {
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      }
      
    }else{
      wx.showModal({
        title: '提示',
        content: '你需要登录，才能享受优惠',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
            app.login(app.globalData.thisshareTicket)
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
    
  },
  getShopkeeperInfo() {
    const that = this
    common.post({
      url: '/app/user/myShop', data: { sessionId: app.globalData.sessionId }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == "0") {
          console.log(res.data.data.status)
          if (res.data.data.status == 2) {
            that.setData({
              isShopkeeper: true
            })

          }
        }
      }).catch((res) => {
        console.log(res)
      })
  },
  favShop() {
    const that = this
    common.post({
      url: '/app/v2/shop/addProduct', data: { sessionId: app.globalData.sessionId, skuId: app.globalData.item.skuId }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == "0") {
          wx.showToast({
            title: '已加入店铺',
            icon: 'success',
            duration: 2000
          })
          that.setData({
            shopHas: true
          })
        }
      }).catch((res) => {
        console.log(res)
      })
  },
  getitemInfo() {
    const that = this
    wx.showLoading({
      title: '加载中',
    })
    common.post({
      url: '/app/goods/getSkuInfoBySkuId', data: { sessionId: app.globalData.sessionId, skuId: this.data.skuId }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          wx.hideLoading()
          if (res.data.sku.images) {
            var imgstr = JSON.parse(res.data.sku.images)
            console.log(imgstr)
          }
          that.setData({
            item: res.data.sku,
            shopHas: res.data.sku.shopHas,
            titletxt: res.data.sku.title,
            itemPic: imgstr,
            thisskuid: res.data.sku.skuId
          })
          app.globalData.item = res.data.sku
          console.log(app.globalData.item)
          wx.setNavigationBarTitle({
            title: res.data.sku.title
          })
          if(app.globalData.userId){
            that.getitemlink()
          }
        } else if (res.data.code == -1) {
          wx.showModal({
            title: '提示',
            content: '商品不存在',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                console.log('用户点击确定')
              }
            }
          })
        } else if (res.data.code == -2) {
          wx.showModal({
            title: '提示',
            content: '商品已过期',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                console.log('用户点击确定')
                // wx.switchTab({
                //   url: '/pages/itemlist/itemlist',
                //   success: function (res) {
                //     console.log(res)
                //   },
                //   fail: function (res) {
                //     console.log(res)
                //   }
                // })
              }
            }
          })
        }
      }).catch((res) => {
        console.log(res)
      })
  },
  runProcess(res){
    const that = this
    // if (app.globalData.newuser) {
    //   console.log("newuser")
    //   this.setData({
    //     novice: true,
    //     step1: true,
    //     newuser: app.globalData.newuser
    //   })
    //   if (that.data.freeId !== '') {
    //     console.log('yes')
    //     this.setData({
    //       hisactive: false
    //     })
    //     that.getfreestatus()
    //   } else {
    //     console.log('no')
    //     this.setData({
    //       hisactive: true
    //     })
    //   }
    //   app.globalData.newuser = false
    //   console.log('newuser:' + app.globalData.newuser, this.data.newuser)

    // } else {
    //   console.log(app.globalData.userInfo.userId)
    //   if (that.data.freeId !== '' && parseInt(this.data.fromUserId) !== parseInt(app.globalData.userInfo.userId)) {
    //     console.log('hisactive')
    //     this.setData({
    //       hisactive: true,
    //       user: app.globalData.userInfo,
    //     })
    //     that.getfreestatus()
    //   } else if (that.data.freeId == '') {
    //     console.log('noUser')
    //     this.getitemstatus()
    //     console.log(app.globalData.userInfo)
    //     this.setData({
    //       user: app.globalData.userInfo,
    //     })
    //   } else {
    //     console.log('myactive')
    //     console.log('freeid:' + that.data.freeId)
    //     console.log('yes')
    //     this.setData({
    //       myactive: true
    //     });
    //     that.getfreestatus()
    //   }
    // }
    // this.getShopkeeperInfo()
    console.log(app.globalData.userInfo.userId)
    if (that.data.freeId !== '' && parseInt(this.data.fromUserId) !== parseInt(app.globalData.userInfo.userId)) {
      console.log('hisactive')
      this.setData({
        hisactive: true,
        user: app.globalData.userInfo,
      })
      that.getfreestatus()
    } else if (that.data.freeId == '') {
      console.log('noUser')
      this.getitemstatus()
      console.log(app.globalData.userInfo)
      this.setData({
        user: app.globalData.userInfo,
      })
    } else {
      console.log('myactive')
      console.log('freeid:' + that.data.freeId)
      console.log('yes')
      this.setData({
        myactive: true
      });
      that.getfreestatus()
    }
    
    let promise = new Promise((resolve, reject) => {
      let timer = setInterval(() => {
        // console.log(app.globalData.sessionId,app.globalData.userId)
        if (that.data.item == []) {
          clearInterval(timer);
          resolve(that.data);
          that.getitemlink()
          that.active()
        } else {
          //todo 信息构建中
        }
      }, 250);
    });
    console.log(app.globalData.isdetail)
    this.getnineitemdata(1)
    let isIphoneX = app.globalData.isIphoneX;
    this.setData({
      isIphoneX: isIphoneX
    })
  },
  waitLogin(res) {
    const that = this
    this.runLogin()
    let promise = new Promise((resolve, reject) => {
      let timer = setInterval(() => {
        // console.log(app.globalData.sessionId,app.globalData.userId)
        if (app.globalData.sessionId && app.globalData.userId) {
          clearInterval(timer);
          resolve(app.globalData);
          this.runProcess(res)
        } else {
          //todo 信息构建中
          that.setData({
            hasLoginTc: false
          })
        }
      }, 250);
    });

  },
  loginTip() {
    const that = this
    console.log(this.data.hasLoginTc)
    if (this.data.hasLoginTc) {
      this.setData({
        hasLoginTc: false
      })
      wx.showModal({
        title: '提示',
        content: '你需要登录，才能享受优惠',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
            wx.showLoading({
              title: '登录中...',
            })
            that.runLogin()
          } else if (res.cancel) {
            console.log('用户点击取消')
            that.setData({
              hasLoginTc: true
            })
          }
        }
      })
    }

  },
  runLogin() {
    const that = this
    let res = app.login(app.globalData.thisshareTicket)
    let promise = new Promise((resolve, reject) => {
      let timer = setInterval(() => {
        // console.log(app.globalData.sessionId,app.globalData.userId)
        if (that.data.sessionId && app.globalData.userId) {
          clearInterval(timer);
          resolve(app.globalData);
          console.log('登录')
          that.getSolitaireData()
          that.getShopData()
        } else {
          //todo 信息构建中
        }
      }, 250);
    });
  },
  toStore() {
    wx.navigateTo({
      url: '/pages/shareShop/shareShop?userId=' + this.data.fromUserId,
      success: function (res) {
        console.log('toStore')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  toUsercenter() {
    wx.switchTab({
      url: '/pages/usercenter/usercenter',
      success: function (res) {
        app.globalData.fromShopkeeper = true
        console.log('toUsercenter')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  toMyStone() {
    wx.switchTab({
      url: '/pages/myStore/myStore',
      success: function (res) {
        console.log('toMyStore')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  showShare(e){
    console.log(e)
    if(this.data.loaded){
      this.setData({
        // sharetc: true,
        actionSheetHidden: false,
        shareData: e.currentTarget.dataset.item,
        formId: e.detail.formId
      });
      console.log(this.data.shareData)
    }else{
      wx.showModal({
        title: '提示',
        content: '你需要登录，才能享受优惠',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
            app.login(app.globalData.thisshareTicket)
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },
  listenerActionSheet: function () {
    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden,
    })
  },
  jlshare(){
    const that = this
    wx.navigateTo({
      url: '/pages/createSolitaire/createSolitaire',
      events: {
        acceptDataFromOpenedPage: function (data) {
          console.log(data)
        },
        someEvent: function (data) {
          console.log(data)
        }
      },
      success: function (res) {
        console.log('toCreateSolitaire')
        res.eventChannel.emit('acceptDataFromOpenerPage', { data: that.data.item })
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  saveSharePic(){
    wx.saveImageToPhotosAlbum({
      filePath: this.data.imgSrc,
      success: function (data) {
          wx.showToast({
              title: '保存成功',
              icon: 'success',
              duration: 2000
          })
      },
      fail: function (err) {
          console.log(err);
          if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              console.log("当初用户拒绝，再次发起授权")
              wx.openSetting({
                  success(settingdata) {
                      console.log(settingdata)
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                          console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                      } else {
                          console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                      }
                  }
              })
          } else {
              wx.showToast({
                  title: '保存失败',
                  icon: 'none'
              });
          }
      },
      complete(res) {
          console.log(res);
      }
    })
  },
  toIndex(){
    wx.switchTab({
      url: '/pages/itemlist/itemlist?userId=' + this.data.fromUserId,
      success: function (res) {
        console.log('toItemlist')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  closeSharePic(){
    console.log('关闭')
    this.setData({
      showshareBox: false
    })
  },
  helpClick(){
    app.globalData.transferuserId = this.data.fromUserId
    app.globalData.transferskuId = this.data.skuId
    app.login()
  },
  closeTip(){
    this.setData({
      tipfirst1: false
    })
    wx.setStorage({
      key:"tipfirst1",
      data:false
    })
  }
})
